/**
 * src/controller/AgentController.ts
 * 核心控制器 - 负责协调 View, Agent Service 和 Tool Service
 */

import * as vscode from 'vscode';
import { IAgentBus } from '../bus/IAgentBus';
import { WebviewToExtensionMessage } from '../types/types';
import { AgentToolGateway } from '../tools/AgentToolGateway';
import { IAgentView } from '../webview/IAgentView';
import { ErrorHandler, ErrorLevel } from '../utils/ErrorHandler';

// 1. 引入通用接口和 Mock 实现
import { IAgentService, IAgentCallbacks, AgentToolRequest } from '../services/IAgentService';
import { MockAgentService } from '../services/MockAgentService';
import { SessionStore } from '../store/SessionStore';

export class AgentController {
    
    private toolService: AgentToolGateway;
    // 2. 依赖抽象接口，而不是具体实现
    private agentService: IAgentService;
    // 持久化存储实例
    private sessionStore: SessionStore; 
    
    constructor(
        private readonly context: vscode.ExtensionContext,
        private readonly messenger: IAgentBus,
        private readonly view: IAgentView
    ) {
        // 初始化工具服务
        this.toolService = new AgentToolGateway(this.messenger);
        
        // 3. 注入 Mock 服务 (未来可根据配置切换为 WebAgentService 或 OpenAIAgentService)
        // 目前为了验证流程，直接使用 MockAgentService
        this.agentService = new MockAgentService();

        this.sessionStore = new SessionStore(); // 初始化 Store (生命周期跟随 Controller)

        // 订阅前端消息
        this.messenger.subscribe(this.handleMessage.bind(this));
        
        // 初始化 Agent 服务
        this.agentService.initialize();
    }

    /**
     * 统一消息处理入口
     */
    private async handleMessage(message: WebviewToExtensionMessage): Promise<void> {
        await ErrorHandler.wrapAsync(
            async () => {
                await this._handleMessageInternal(message);
            },
            'Failed to handle webview message',
            { level: ErrorLevel.Error }
        );
    }

    /**
     * 内部消息处理逻辑
     */
    private async _handleMessageInternal(message: WebviewToExtensionMessage): Promise<void> {
        switch (message.type) {
            case 'sendMessage':
                await this.handleUserMessage(message.text, message.attachments);
                return;

            case 'callTool':
                await this.handleManualToolCall(message.toolId, message.args);
                return;

            case 'clearChat':
                this.sessionStore.clear(); // 清空 Store
                await this.view.notifyChatCleared();
                return;

            case 'requestToolList':
                await this.view.updateToolList(this.toolService.getToolList());
                return;

            case 'requestContext':
                const files = await this.toolService.requestFiles();
                if (files) {
                    await this.view.notifyFilesSelected(files);
                }
                return;

            case 'webviewReady':
                //  恢复对话历史
                const history = this.sessionStore.getHistory();
               if (history.length > 0) {
                    await this.view.restoreHistory(history);
                }
                // 恢复手动工具执行历史
                const manualHistory = this.sessionStore.getManualHistory();
                if (manualHistory.length > 0) {
                    await this.view.restoreManualHistory(manualHistory);
                }
                return;
        }
    }

    /**
     * 处理用户发送的消息 (AI 对话核心流程)
     */
    private async handleUserMessage(text: string, attachments?: any[]): Promise<void> {
        await ErrorHandler.wrapAsync(
            async () => {
                await this._handleUserMessageInternal(text, attachments);
            },
            'Failed to process user message',
            { level: ErrorLevel.Warning }
        );
    }

    /**
     * 内部用户消息处理逻辑
     */
    private async _handleUserMessageInternal(text: string, attachments?: any[]): Promise<void> {

        // 1. 记录用户消息
        const userMsg = SessionStore.createMessage('user', text, { attachments });
        this.sessionStore.addMessage(userMsg);

        // 1. 生成消息 ID
        const aiMessageId = `msg_${Date.now()}`;
        // 在 Store 中预先创建 AI 消息占位
        const aiMsg = SessionStore.createMessage('assistant', '', { id: aiMessageId });
        aiMsg.status = 'streaming';
        this.sessionStore.addMessage(aiMsg);

        let accumulatedText = '';

        // 2. 定义通用回调，适配 IAgentCallbacks 接口
        const callbacks: IAgentCallbacks = {
            onChunk: async (chunk) => {
                accumulatedText += chunk;
                // 实时更新 Store 中的消息内容
                this.sessionStore.updateMessage(aiMessageId, { content: accumulatedText });
                await this.view.streamAssistantResponse(aiMessageId, chunk);
            },
            onToolRequest: async (toolRequests) => {
                // Agent 决定调用工具
                // 1. 清除之前的流式文本（如果需要转为工具状态）
                await this.view.clearStreamMessage(aiMessageId);
                // 标记 AI 消息结束
                this.sessionStore.updateMessage(aiMessageId, { status: 'sent' });
                // 处理工具链
                await this.handleAIToolChain(toolRequests, callbacks);
            },
            onError: async (error) => {
                this.sessionStore.updateMessage(aiMessageId, { status: 'error' });
                await this.view.showErrorMessage(`Agent Error: ${error.message}`);
            }
        };

        // 3. 发送给通用的 Agent 服务
        await this.agentService.sendMessage(text, attachments, callbacks);
    }

    /**
     * 处理 Agent 触发的工具调用链
     * @param toolRequests 通用的工具请求列表
     * @param callbacks 回调接口
     */
    private async handleAIToolChain(
            toolRequests: AgentToolRequest[], 
            callbacks: IAgentCallbacks
        ): Promise<void> {
        const toolResults: { toolCallId: string; output: string }[] = [];

        for (const req of toolRequests) {
            // 记录 AI 触发的工具调用
            const callMsg = SessionStore.createMessage('tool-call', `Calling tool: ${req.toolName}`, {
                id: req.id,
                toolResult: { 
                    callId: req.id,
                    success: true,
                    output: 'Running...'
                }
            });
            this.sessionStore.addMessage(callMsg);

            try {
                const result = await this.toolService.requestToolExecution({
                    id: req.id,
                    toolName: req.toolName,
                    args: req.toolArgs
                });

                // 标记为 AI 调用
                result.source = 'ai';

                await this.view.showToolResult(result);
                
                // 更新 Store
                this.sessionStore.updateMessage(req.id, { 
                    type: 'tool-result',
                    content: `Tool ${req.toolName} executed`,
                    toolResult: result 
                });
                
                toolResults.push({
                    toolCallId: req.id,
                    output: result.output || result.error || 'No output'
                });

            } catch (error: any) {
                const errorMsg = error instanceof Error ? error.message : String(error);
                await this.view.showErrorMessage(`Tool execution failed: ${errorMsg}`);
                
                // 错误也要记录
                this.sessionStore.updateMessage(req.id, {
                    type: 'tool-result',
                    content: `Tool execution failed`,
                    toolResult: { callId: req.id, success: false, error: errorMsg, duration: 0 }
                });

                toolResults.push({ toolCallId: req.id, output: errorMsg });
            }
        }

        await this.agentService.processToolResults(toolResults, callbacks);
    }

   /**
     * 处理前端手动触发的工具调用
     */
    private async handleManualToolCall(toolId: string, args?: any): Promise<void> {
        await ErrorHandler.wrapAsync(
            async () => {
                await this._handleManualToolCallInternal(toolId, args);
            },
            `Failed to execute tool: ${toolId}`,
            { level: ErrorLevel.Warning }
        );
    }

    /**
     * 内部手动工具调用逻辑
     */
    private async _handleManualToolCallInternal(toolId: string, args?: any): Promise<void> {
        // 1. 直接执行工具
        const result = await this.toolService.executeToolDirectly(toolId, args);
        
        // 标记为手动调用
        result.source = 'manual';
        
        // 2. 显示结果
        await this.view.showToolResult(result);

        // ============================================================
        // [关键修改] 3. 记录到 SessionStore
        // ============================================================
        
        // 获取工具名称 (用于历史记录显示)
        const tools = this.toolService.getToolList();
        const toolDef = tools.find(t => t.id === toolId);
        const toolName = toolDef ? toolDef.name : toolId;

        this.sessionStore.addManualHistory({
            id: `hist_${Date.now()}`,
            toolId: toolId,
            toolName: toolName,
            args: args,
            result: result,
            timestamp: Date.now()
        });
    }

    public async onViewReady(): Promise<void> {
        await this.view.updateToolList(this.toolService.getToolList());
        console.log('[AgentController] View initialized, tool list sent.');
    }

    /**
     * 清理资源,防止内存泄漏
     */
    public dispose(): void {
        // 清理 SessionStore
        this.sessionStore.clear();
        
        // 如果 messenger 有 dispose 方法,调用它
        if ('dispose' in this.messenger && typeof this.messenger.dispose === 'function') {
            (this.messenger as any).dispose();
        }
        
        console.log('[AgentController] Disposed');
    }
}